{% extends "base.html" %}

{% block title %}预约会议{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>预约会议</h2>
    <form id="meetingBookingForm">
        <div class="mb-3">
            <label for="title" class="form-label">会议主题</label>
            <input id="title" name="title" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="start_time" class="form-label">开始时间</label>
            <input id="start_time" name="start_time" type="datetime-local" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="end_time" class="form-label">结束时间</label>
            <input id="end_time" name="end_time" type="datetime-local" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="attendee_count" class="form-label">参会人数</label>
            <input id="attendee_count" name="attendee_count" type="number" min="1" value="1" class="form-control" required>
            <div class="form-text">请输入预计参会人数，系统将筛选出符合容量的会议室</div>
        </div>
        <div class="mb-3">
            <label for="room_id" class="form-label">会议室</label>
            <select id="room_id" name="room_id" class="form-select" required style="cursor: pointer; background-color: white;">
                <option value="">请选择会议室...</option>
            </select>
            <div id="roomCapacityInfo" class="form-text"></div>
        </div>
        <button type="submit" class="btn btn-primary btn-lg">预约会议</button>
        <a href="/rooms" class="btn btn-secondary btn-lg ml-2">返回会议室列表</a>
    </form>
    <div id="createMeetingMsg" class="mt-3"></div>
</div>
{% endblock %}

{% block extrajs %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    initAuth();
    
    // 检查用户登录状态
    const token = localStorage.getItem('token');
    if (!token) {
        document.getElementById('createMeetingMsg').innerHTML = 
            '<div class="alert alert-danger">您还未登录，无法预约会议。正在跳转到登录页面...</div>';
        setTimeout(() => window.location.href = '/login', 1500);
        return;
    }
    
    // 设置axios默认头
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
    
    // 设置默认日期时间
    function pad(num) { return num.toString().padStart(2, '0'); }
    const now = new Date();
    now.setSeconds(0, 0); // 清除秒和毫秒
    // 向上取整到最近的15分钟
    let minutes = now.getMinutes();
    let roundedMinutes = Math.ceil(minutes / 15) * 15;
    if (roundedMinutes === 60) {
        now.setHours(now.getHours() + 1);
        roundedMinutes = 0;
    }
    now.setMinutes(roundedMinutes);
    
    const startDateTime = new Date(now);
    const endDateTime = new Date(now);
    endDateTime.setHours(endDateTime.getHours() + 1);
    
    // 格式化为HTML datetime-local格式 YYYY-MM-DDThh:mm
    function toDatetimeLocal(dt) {
        return dt.getFullYear() + '-' + pad(dt.getMonth() + 1) + '-' + pad(dt.getDate()) + 'T' + pad(dt.getHours()) + ':' + pad(dt.getMinutes());
    }
    document.getElementById('start_time').value = toDatetimeLocal(startDateTime);
    document.getElementById('end_time').value = toDatetimeLocal(endDateTime);
    
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const preSelectedRoomId = urlParams.get('room');
    const attendeeCount = urlParams.get('attendees') || 1;
    
    // 设置初始参会人数
    document.getElementById('attendee_count').value = attendeeCount;
    
    // 保存所有会议室数据
    let allRooms = [];
    
    // 加载会议室
    function loadRooms() {
        const attendeeCount = parseInt(document.getElementById('attendee_count').value) || 1;
        
        // 显示加载中提示
        document.getElementById('roomCapacityInfo').innerHTML = 
            `<span class="text-info">正在加载会议室数据...</span>`;
        
        // 记录当前时间，用于调试
        console.log('开始加载会议室数据:', new Date().toLocaleTimeString());
        
        axios.get('/api/rooms/', {
            params: {
                limit: 100  // 获取更多会议室
            }
        })
        .then(res => {
            console.log('API返回数据:', res.data);
            
            const sel = document.getElementById('room_id');
            allRooms = res.data.rooms || [];
            
            console.log(`成功获取到${allRooms.length}个会议室`);
            
            // 先清空现有选项（保留第一个提示选项）
            while (sel.options.length > 1) {
                sel.remove(1);
            }
            
            if (allRooms.length === 0) {
                const opt = document.createElement('option');
                opt.value = "";
                opt.textContent = "没有可用的会议室";
                opt.disabled = true;
                sel.appendChild(opt);
                
                document.getElementById('createMeetingMsg').innerHTML = 
                    '<div class="alert alert-warning">当前没有可用的会议室，请联系管理员</div>';
                return;
            }
            
            // 按容量排序会议室
            allRooms.sort((a, b) => a.capacity - b.capacity);
            
            // 筛选出符合人数要求的会议室
            const filteredRooms = allRooms.filter(room => room.capacity >= attendeeCount);
            
            if (filteredRooms.length === 0) {
                document.getElementById('roomCapacityInfo').innerHTML = 
                    `<span class="text-danger">没有找到符合${attendeeCount}人的会议室，请减少参会人数或联系管理员</span>`;
            } else {
                document.getElementById('roomCapacityInfo').innerHTML = 
                    `已为您筛选出${filteredRooms.length}个符合${attendeeCount}人的会议室`;
            }
            
            // 添加调试信息，看一下filteredRooms的实际内容
            console.log('筛选后的会议室:', filteredRooms);
            
            // 确保下拉框可点击
            sel.disabled = false;
            
            // 添加会议室选项
            filteredRooms.forEach(room => {
                const opt = document.createElement('option');
                opt.value = room.id;
                opt.textContent = `${room.name} (${room.location}, 容量:${room.capacity}人)`;
                
                // 如果人数超出容量，标记为警告色
                if (room.capacity < attendeeCount) {
                    opt.style.color = '#dc3545';
                    opt.disabled = true;
                }
                
                // 如果有预选会议室，则选中它
                if (preSelectedRoomId && room.id.toString() === preSelectedRoomId) {
                    opt.selected = true;
                }
                
                sel.appendChild(opt);
            });
            
            // 如果没有选中的会议室但有可用会议室，选择第一个
            if (sel.selectedIndex === 0 && filteredRooms.length > 0) {
                sel.selectedIndex = 1;
                // 触发change事件，确保任何依赖于选择的逻辑都能正确执行
                sel.dispatchEvent(new Event('change'));
            }
            
            // 确保表单"预约会议"按钮可用
            document.querySelector('button[type="submit"]').disabled = false;
        })
        .catch(err => {
            console.error('加载会议室失败:', err);
            // 显示更详细的错误信息，方便调试
            let errorMsg = '加载会议室失败';
            if (err.response) {
                // 服务器返回了错误状态码
                errorMsg += `，状态码: ${err.response.status}`;
                if (err.response.data && err.response.data.detail) {
                    errorMsg += `，原因: ${err.response.data.detail}`;
                }
            } else if (err.request) {
                // 请求发送了但没有收到响应
                errorMsg += '，未收到服务器响应';
            } else {
                // 请求设置时发生错误
                errorMsg += `，错误信息: ${err.message}`;
            }
            document.getElementById('createMeetingMsg').innerHTML = 
                `<div class="alert alert-danger">${errorMsg}。请尝试<a href="javascript:location.reload()">刷新页面</a>或检查您是否已登录。</div>`;
            
            document.getElementById('roomCapacityInfo').innerHTML = 
                '<span class="text-danger">无法加载会议室数据</span>';
        });
    }
    
    // 监听参会人数变化
    document.getElementById('attendee_count').addEventListener('change', function() {
        loadRooms();
    });
    
    // 初始加载会议室
    loadRooms();
    
    // 预约会议
    document.getElementById('meetingBookingForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const title = document.getElementById('title').value.trim();
        const start_time = document.getElementById('start_time').value;
        const end_time = document.getElementById('end_time').value;
        const room_id = document.getElementById('room_id').value;
        const attendee_count = parseInt(document.getElementById('attendee_count').value);
        
        console.log('表单数据:', {
            title,
            start_time,
            end_time,
            room_id,
            attendee_count
        });
        
        // 表单验证
        if (!title) {
            document.getElementById('createMeetingMsg').innerHTML = 
                '<div class="alert alert-danger">请输入会议主题</div>';
            return;
        }
        
        if (!start_time || !end_time) {
            document.getElementById('createMeetingMsg').innerHTML = 
                '<div class="alert alert-danger">请选择会议时间</div>';
            return;
        }
        
        if (!room_id) {
            document.getElementById('createMeetingMsg').innerHTML = 
                '<div class="alert alert-danger">请选择会议室</div>';
            // 尝试重新加载会议室列表
            document.getElementById('createMeetingMsg').innerHTML += 
                '<div class="mt-2"><button class="btn btn-outline-primary btn-sm" onclick="loadRooms()">重新加载会议室列表</button></div>';
            return;
        }
        
        // 检查所选会议室容量是否足够
        const selectedRoom = allRooms.find(room => room.id.toString() === room_id);
        if (selectedRoom && selectedRoom.capacity < attendee_count) {
            document.getElementById('createMeetingMsg').innerHTML = 
                `<div class="alert alert-danger">所选会议室容量(${selectedRoom.capacity}人)不足，无法容纳${attendee_count}人</div>`;
            return;
        }
        
        // 显示加载提示
        document.getElementById('createMeetingMsg').innerHTML = 
            '<div class="alert alert-info">正在提交，请稍候...</div>';
        
        const data = {
            title: title,
            start_time: start_time,
            end_time: end_time,
            room_id: parseInt(room_id),
            attendee_count: attendee_count
        };
        
        // 记录将要提交的数据
        console.log('提交数据:', data);
        
        axios.post('/api/meetings/', data)  // 确保使用正确的API路径
            .then(res => {
                console.log('预约成功:', res.data);
                document.getElementById('createMeetingMsg').innerHTML = 
                    '<div class="alert alert-success">会议预约成功！正在跳转到我的会议...</div>';
                setTimeout(() => window.location.href = '/my-meetings', 1500);
            })
            .catch(err => {
                console.error('预约失败:', err);
                let errorDetails = '';
                if (err.response) {
                    errorDetails = err.response.data.detail || JSON.stringify(err.response.data);
                } else if (err.request) {
                    errorDetails = '服务器未响应';
                } else {
                    errorDetails = err.message || '未知错误';
                }
                
                document.getElementById('createMeetingMsg').innerHTML = 
                    `<div class="alert alert-danger">预约失败：${errorDetails}</div>`;
            });
    });
});
</script>
{% endblock %} 